<script setup>
import { ref, computed } from 'vue'
import { getGoodsByIdAPI } from '@/services/category'
import { onLoad, onHide } from '@dcloudio/uni-app'
import SokachGoodsSkeleton from '@/components/sokach-goods-skeleton.vue'
import SokachAddress from '@/components/sokach-address.vue'
import SokachService from '@/components/sokach-service.vue'
import VkDataGoodsSkuPopup from '@/components/vk-data-goods-sku-popup.vue'
import { storeToRefs } from 'pinia'
import { useAddressStore } from '@/stores/index'
import { postMemberCartAPI } from '@/services/cart'

//接收参数
const props = defineProps({
  id: String,
})

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

//轮播图
const bannerImgList = ref([])

//当前图片下标
const current = ref(0)

//手动切换轮播图
const onChangeSwiper = (e) => {
  current.value = e.current
}

//点击轮播图
const onSwiperitem = () => {
  //图片预览
  uni.previewImage({
    current: current.value,
    urls: bannerImgList.value,
  })
}

//获取商品信息
const goodsList = ref({})
const getGoodsData = async () => {
  //调用接口
  const res = await getGoodsByIdAPI(props.id)
  goodsList.value = res.result

  //轮播图数据
  bannerImgList.value = res.result.mainPictures

  // SKU组件所需格式
  localdata.value = {
    //商品id
    _id: res.result.id,
    //商品名称
    name: res.result.id.name,
    //商品头像
    goods_thumb: res.result.mainPictures[0],
    //商品规格列表
    spec_list: res.result.specs.map((item) => ({ name: item.name, list: item.values })),
    //该商品对应的sku列表
    sku_list: res.result.skus.map((item) => {
      return {
        // SKU ID
        _id: item.id,
        // 商品ID
        goods_id: res.result.id,
        // 商品名称
        goods_name: res.result.name,
        // SKU头像
        image: item.picture,
        // SKU 价格 注意：需要乘以 100
        price: item.price * 100,
        //库存
        stock: item.inventory,
        // 该SKU由哪些规格组成（规格是有顺序的，需要与spec_list的数组顺序对应）
        sku_name_arr: item.specs.map((v) => v.valueName),
      }
    }),
  }
}

//弹出层
const popup = ref(null)

//选中的弹出层
const popupList = ref('')

//点击地址事件
const onChangePopup = (type) => {
  //点击打开地址请求地址列表详情
  if (type === 'Address') {
    addressStore.getMemberAddressData()
  }
  popupList.value = type
  popup.value.open()
}

//关闭弹出层
const onClose = () => {
  popup.value.close()
}

// 是否显示SKU组件
const isShowSku = ref(false)

// 商品信息
const localdata = ref({})

//按钮模式
const mode = ref(2)

// 打开SKU弹窗修改按钮模式
const openSkuPopup = (val) => {
  // 显示SKU弹窗
  isShowSku.value = true
  // 修改按钮模式
  mode.value = val
}

// SKU组件实例
const skuPopupRef = ref(null)

// 计算被选中的值
const selectArrText = computed(() => {
  return skuPopupRef.value.selectArr[0] || '请选择商品规格'
})

//选择收货地址
const addressStore = useAddressStore()
const { addressList, defaultAddress, address } = storeToRefs(addressStore)

//加入购物车事件
const onAddCart = async ({ _id, buy_num }) => {
  await postMemberCartAPI({ skuId: _id, count: buy_num })
  uni.showToast({ title: '添加成功' })
  isShowSku.value = false
}

// 立即购买
const onBuyNow = (ev) => {
  uni.navigateTo({ url: `/pagesOrder/create/create?skuId=${ev._id}&count=${ev.buy_num}` })
}

//加载中标记
const isLoading = ref(false)

//页面加载
onLoad(async () => {
  isLoading.value = true
  await getGoodsData()
  isLoading.value = false
})
//页面隐藏
onHide(() => {
  onClose()
})
</script>

<template>
  <!-- 骨架屏 -->
  <SokachGoodsSkeleton v-if="isLoading"></SokachGoodsSkeleton>

  <scroll-view scroll-y class="goods" v-else>
    <!-- 轮播图 -->
    <u-swiper
      height="750rpx"
      class="banner"
      indicatorStyle="right: 20px"
      :list="bannerImgList"
      @change="onChangeSwiper"
      radius="0"
      :autoplay="false"
      @click="onSwiperitem"
      circular
    >
      <template #indicator>
        <view class="indicator-num">
          <text class="indicator-num__text">{{ current + 1 }}/{{ bannerImgList.length }}</text>
        </view>
      </template>
    </u-swiper>
    <!-- 商品简介 -->
    <view class="meta">
      <view class="price">
        <text class="symbol">¥</text>
        <text class="number">{{ goodsList.price }}</text>
      </view>
      <view class="name ellipsis">{{ goodsList.name }} </view>
      <view class="desc">
        {{ goodsList.desc }}
      </view>
    </view>
    <!-- 操作面板 -->
    <view class="action">
      <view class="item" @click="openSkuPopup(1)">
        <view class="dec">
          <text class="label">选择</text>
          <text class="text ellipsis">{{ selectArrText }}</text>
        </view>
        <u-icon name="arrow-right" color="#ccc" size="18"></u-icon>
      </view>
      <view class="item" @click="onChangePopup('Address')">
        <view class="dec">
          <text class="label">选择</text>
          <text class="text" v-if="!address.receiver">请选择收货地址</text>
          <text class="text ellipsis" v-else>{{ address.fullLocation }} {{ address.address }}</text>
        </view>
        <u-icon name="arrow-right" color="#ccc" size="18"></u-icon>
      </view>
      <view class="item" @click="onChangePopup('Service')">
        <view class="dec">
          <text class="label">服务</text>
          <text class="text ellipsis">无忧退 快速退款 免费包裹</text>
        </view>
        <u-icon name="arrow-right" color="#ccc" size="18"></u-icon>
      </view>
    </view>
    <!-- 详情 -->
    <view class="detail">
      <view class="top">
        <view class="title">
          <view class="icon"></view>
          <text class="txt">详情</text>
        </view>
        <view class="item" v-for="(item, index) in goodsList?.details?.properties" :key="index">
          <view class="label">{{ item.name }}</view>
          <text class="dec">{{ item.value }}</text>
        </view>
      </view>
      <image
        v-for="item in goodsList?.details?.pictures"
        :key="item"
        mode="widthFix"
        :src="item"
        class="image-item"
      />
    </view>
    <!-- 同类推荐 -->
    <view class="detail similar">
      <view class="top">
        <view class="title">
          <view class="icon"></view>
          <text class="txt">同类推荐</text>
        </view>
      </view>
      <view class="content">
        <navigator
          v-for="item in goodsList?.similarProducts"
          :key="item.id"
          class="goods"
          hover-class="none"
          :url="`/pages/goods/goods?id=${item.id}`"
        >
          <image class="image" mode="aspectFill" :src="item.picture"></image>
          <view class="name ellipsis">{{ item.name }}</view>
          <view class="price">
            <text class="symbol">¥</text>
            <text class="number">{{ item.price }}</text>
          </view>
        </navigator>
      </view>
    </view>
  </scroll-view>

  <!-- 用户操作 -->
  <view class="toolbar" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
    <view class="icons">
      <button class="icons-button"><text class="icon-heart"></text>收藏</button>
      <button class="icons-button" open-type="contact">
        <text class="icon-handset"></text>客服
      </button>
      <navigator class="icons-button" url="/pages/cart/cart"
        ><text class="icon-cart"></text>购物车</navigator
      >
    </view>
    <view class="buttons">
      <view class="addcart" @click="openSkuPopup(2)"> 加入购物车 </view>
      <view class="payment" @click="openSkuPopup(3)"> 立即购买 </view>
    </view>
  </view>

  <!-- 弹出层 -->
  <uni-popup ref="popup" type="bottom" background-color="#fff">
    <SokachAddress
      v-show="popupList === 'Address'"
      @close="onClose"
      :address-list="addressList"
      :default-address="defaultAddress"
    ></SokachAddress>
    <SokachService v-show="popupList === 'Service'" @close="onClose"></SokachService>
  </uni-popup>

  <!-- SKU弹窗组件 -->
  <VkDataGoodsSkuPopup
    v-model="isShowSku"
    :localdata="localdata"
    :mode="mode"
    add-cart-background-color="#FFA868"
    buy-now-background-color="#27BA9B"
    ref="skuPopupRef"
    @add-cart="onAddCart"
    @buy-now="onBuyNow"
    :actived-style="{
      color: '#27BA9B',
      borderColor: '#27BA9B',
      backgroundColor: '#E9F8F5',
    }"
  ></VkDataGoodsSkuPopup>
</template>

<style lang="scss">
page {
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}
.goods {
  background-color: #f4f4f4;
}
.indicator {
  @include flex(row);
  justify-content: center;

  &__dot {
    height: 6px;
    width: 6px;
    border-radius: 100px;
    background-color: rgba(255, 255, 255, 0.35);
    margin: 0 5px;
    transition: background-color 0.3s;

    &--active {
      background-color: #ffffff;
    }
  }
}

.indicator-num {
  padding: 2px 0;
  background-color: rgba(0, 0, 0, 0.35);
  border-radius: 100px;
  width: 35px;
  @include flex;
  justify-content: center;

  &__text {
    color: #ffffff;
    font-size: 12px;
  }
}
.meta {
  position: relative;
  border-bottom: 1rpx solid #eaeaea;
  background-color: #fff;
  .price {
    height: 130rpx;
    padding: 25rpx 30rpx 0;
    color: #fff;
    font-size: 34rpx;
    box-sizing: border-box;
    background-color: #35c8a9;
  }
  .number {
    font-size: 56rpx;
  }
  .brand {
    width: 160rpx;
    height: 80rpx;
    overflow: hidden;
    position: absolute;
    top: 26rpx;
    right: 30rpx;
  }
  .name {
    max-height: 88rpx;
    line-height: 1.4;
    margin: 20rpx;
    font-size: 32rpx;
    color: #333;
  }
  .desc {
    line-height: 1;
    padding: 0 20rpx 30rpx;
    font-size: 24rpx;
    color: #cf4444;
  }
}
.action {
  background-color: #fff;
  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 100rpx;
    margin-left: 30rpx;
    padding-right: 20rpx;
    border-bottom: 1rpx solid #eaeaea;
    font-size: 26rpx;
    color: #333;
    &:last-child {
      border-bottom: none;
    }
  }
  .dec {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .label {
    width: 80rpx;
    color: #898b94;
    margin: 0 16rpx 0 10rpx;
  }
  .text {
    flex: 1;
    -webkit-line-clamp: 1;
  }
}
.detail {
  margin-top: 20rpx;
  background-color: #fff;

  .top {
    padding-left: 20rpx;
    padding-top: 30rpx;
  }
  .title {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;

    .icon {
      margin-right: 10rpx;
      height: 30rpx;
      width: 3rpx;
      background-color: #35c8a9;
    }
    .txt {
      font-weight: bold;
    }
  }
  .item {
    min-height: 100rpx;
    margin-right: 20rpx;
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx dashed #ccc;
    font-size: 26rpx;
    color: #333;

    &:last-child {
      margin-bottom: 30rpx;
    }
    .dec {
      // display: flex;
      flex: 1;
      line-height: 2;
    }
    .label {
      width: 200rpx;
    }
  }
  .image-item {
    width: 100%;
  }
}

.content {
  background-color: #f4f4f4;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 0 20rpx;
  navigator {
    width: 345rpx;
    padding: 24rpx 20rpx 20rpx;
    margin-top: 20rpx;
    margin-bottom: 15rpx;
    border-radius: 10rpx;
    background-color: #fff;
    float: left;
  }
  .image {
    width: 100%;
    height: 260rpx;
  }
  .name {
    height: 80rpx;
    margin: 10rpx 0;
    font-size: 26rpx;
    color: #262626;
  }
  .price {
    line-height: 1;
    font-size: 20rpx;
    color: #cf4444;
  }
  .number {
    font-size: 26rpx;
    margin-left: 2rpx;
  }
}
navigator {
  &:nth-child(even) {
    margin-right: 0;
  }
}
/* 底部工具栏 */
.toolbar {
  background-color: #fff;
  height: 100rpx;
  padding: 0 20rpx;
  border-top: 1rpx solid #eaeaea;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: content-box;
  .buttons {
    display: flex;
    & > view {
      width: 220rpx;
      text-align: center;
      line-height: 72rpx;
      font-size: 26rpx;
      color: #fff;
      border-radius: 72rpx;
    }
    .addcart {
      background-color: #ffa868;
    }
    .payment {
      background-color: #27ba9b;
      margin-left: 20rpx;
    }
  }
  .icons {
    padding-right: 10rpx;
    display: flex;
    align-items: center;
    flex: 1;
    .icons-button {
      flex: 1;
      text-align: center;
      line-height: 1.4;
      padding: 0;
      margin: 0;
      border-radius: 0;
      font-size: 20rpx;
      color: #333;
      background-color: #fff;
    }
    text {
      display: block;
      font-size: 34rpx;
    }
  }
}
</style>
